const plugin = requirePlugin('WechatSI');

class PluginService {
  innerAudioContext;

  audioBroadcast(content){
    return new Promise((resolve, reject) => {
      this.innerAudioContext = wx.createInnerAudioContext();
      plugin.textToSpeech({
        // 调用插件的方法
        lang: 'zh_CN',
        content,
        success: res => {
          this.playAudio(res.filename, resolve, reject);
        },
        fail: reject
      });
    });
  }

  playAudio(e, resolve, reject) {
    this.innerAudioContext.src = e;
    this.innerAudioContext.play();

    this.innerAudioContext.onStop(() => {
      console.log('[ onStop ] >');
      resolve({
        type: 'stop'
      });
    });

    this.innerAudioContext.onEnded(() => {
      //播放结束，销毁该实例
      this.innerAudioContext.destroy();

      console.log('[ onEnded ] >');

      resolve({
        type: 'end'
      });
    });

    this.innerAudioContext.onError(error => {
      console.log('[ onError ] >', error);

      this.innerAudioContext.destroy();
      reject(error);
    });
  }

  stopAudio() {
    this.innerAudioContext?.stop();
    this.innerAudioContext?.destroy();
  }
}

export default new PluginService();
